#
# peerscape.http.color
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Toni Ruottu <toni.ruottu@iki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import random

def get_safety_color(db):
    try:
        color = db.get_local_info('color')
    except LookupError:
        color = get_new_safety_color()
        db.set_local_info('color', color)

    return color

def get_new_safety_color():

    # color weight calibration (%)

    rw = 30
    gw = 59 
    bw = 11

    assert rw + gw + bw == 100, 'total color weight exceeds 100'

    # limits

    ls = '#9aa' # light
    ds = '#99a' # dark

    l = int(ls[1], 16)*rw + int(ls[2], 16)*gw + int(ls[3], 16)*bw
    d = int(ds[1], 16)*rw + int(ds[2], 16)*gw + int(ds[3], 16)*bw

    colors = ['#%x%x%x' % (r,g,b)
              for r in range(16)
              for g in range(16)
              for b in range(16)
              if d < r*rw + g*gw + b*bw < l]

    return random.choice(colors)
